package cn.dt67.controller;

import cn.dt67.pojo.User;
import cn.dt67.service.RoleService;
import cn.dt67.service.UserService;
import cn.dt67.utils.Constrant;
import cn.dt67.utils.PageHelper;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    
    private static final Logger logger = Logger.getLogger(UserController.class);
    
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    
    @RequestMapping("/show")
    public String show(Model model) {
        model.addAttribute("userList", userService.getAllUser());
        return "show";
    }
    
    /**
     * 跳转至登陆页
     */
    @RequestMapping("/login")
    public String login(HttpSession session) {
        
        if (session.getAttribute(Constrant.USER_SESSION) != null) {
            User user = (User) session.getAttribute("userSession");
            logger.debug("该用户" + user.getUserName() + "已登陆，跳转至首页==========》");
            return "redirect:/user/main";
        }
        
        logger.debug("跳转至登陆页==========》");
        
        return "login";
    }
    
    /**
     * 处理登陆
     */
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode,
                          @RequestParam String userPassword,
                          HttpSession session) {
        //后台校验用户登陆；
        logger.debug("开始后台登陆校验=========》");
        User user = userService.findUser(userCode, userPassword);
        if (user.getUserCode() == null || user.getUserPassword() == null) {
            //检验失败，回首页
            logger.debug("后台登陆校验为空=========》");
            //存入session
            return "login";
        }
        session.setAttribute(Constrant.USER_SESSION, user);
        logger.debug("后台登陆校验成功=========》");
        return "frame";
    }
    
    @RequestMapping("/main")
    public String main(HttpSession session) {
        if (session.getAttribute(Constrant.USER_SESSION) == null) {
            User user = (User) session.getAttribute("userSession");
            logger.debug("该用户" + user.getUserName() + "未登陆，跳转至登陆页==========》");
            return "redirect:/user/login";
        }
        return "frame";
    }
    
    /**
     * 注销方法
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constrant.USER_SESSION);
        return "login";
    }
    
    @RequestMapping("/userlist")
    public String getUserList(Model model,
                              @RequestParam(value = "queryname", required = false) String queryname,
                              @RequestParam(value = "queryUserRole", required = false) String queryUserRole,
                              @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        //查询所有的角色信息
        int roleId = 0;
        if (queryUserRole != null && !queryUserRole.equals("")) {
            roleId = Integer.valueOf(queryUserRole);
        }
        
        
        //增加分页的内容
        int currentPaheNo = 0;
        PageHelper ph = new PageHelper();
        if (pageIndex != null) {
            currentPaheNo = Integer.parseInt(pageIndex);
            ph.setCurrentPageNo(currentPaheNo);
        }
        int pageSize = ph.getPageSize();
        //调用servce接口查询总条数
        int totalCount = userService.getUserCount(queryname, roleId);
        ph.setTotalCount(totalCount);//为了更新总页数
        currentPaheNo = ph.getCurrentPageNo();
        int totalPageCount = ph.getTotalPageCount();
        
        model.addAttribute("roleList", roleService.findAll());
        model.addAttribute("userList", userService.findUserList(queryname, roleId, currentPaheNo, pageSize));
        model.addAttribute("queryname", queryname);
        model.addAttribute("queryUserRole", queryUserRole);
        //add by hjj ：添加分页的信息
        model.addAttribute("currentPageNo", currentPaheNo);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPageCount", totalPageCount);
        return "user/userlist";
    }
    
    /**
     * 用户插入：属性绑定
     * 1）进入表单前，把user对象放入model
     */
    /*@RequestMapping(value = "/add",method = RequestMethod.GET)
    public String go2UserAdd(Model model){
        User user = new User();
        model.addAttribute("user",user);
        return "user/useradd";
    }*/
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String go2UserAdd(@ModelAttribute("user") User user, Model model) {
//        User user = new User();
//        model.addAttribute("user",user);
        return "user/useradd";
    }
    /*@RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(User user,HttpSession session){
//        System.out.println(user.getUserName());
        User currentUser = (User)session.getAttribute(Constrant.USER_SESSION);
        user.setCreatedBy(currentUser.getId());
        //调用保存方法
        if(userService.addNewUser(user)){
            //重定向到用户查询列表
            return "redirect:/user/userlist";
        }
        return "user/useradd";//失败
    }*/
    
    /**
     * 利用spring fm标签自动提交表单
     */
    @RequestMapping(value = "/add2", method = RequestMethod.GET)
    public String go2UserAdd2(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "user/useradd2";
    }
    
    /**
     * 校验的过程发生在：前端控制器分发后，到达处理方法（hanler）之前
     * ***后台校验
     *
     * @param user
     * @param bindingResult
     * @param session
     * @return
     */
    @RequestMapping(value = "/add2", method = RequestMethod.POST)
    public String add2(@Valid User user, BindingResult bindingResult, HttpSession session) {
        
        if (bindingResult.hasErrors()) {
            return "user/useradd2";
        }
        
        User currentUser = (User) session.getAttribute(Constrant.USER_SESSION);
        user.setCreatedBy(currentUser.getId());
        //调用保存方法
        if (userService.addNewUser(user)) {
            //重定向到用户查询列表
            return "redirect:/user/userlist";
        }
        return "user/useradd2";
    }
    
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public String go2modify(@RequestParam("userId") String userId, Model model) {
        //根据userId查询user信息
//        System.out.println(userId);
        if (userId == null || userId.equals("")) {
            logger.debug("不是合法的查询的id=============》");
            return "redirect:/user/userlist";
        }
        model.addAttribute("user", userService.findById(Integer.parseInt(userId)));
        return "user/usermodify";
    }
    
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public String modify(User user, HttpSession session) {
//        System.out.println(user.getUserName());
        User currentUser = (User) session.getAttribute(Constrant.USER_SESSION);
        user.setModifyBy(currentUser.getId());
        if (userService.update(user)) {
            logger.debug("更新用户信息成功！=============》");
            return "redirect:/user/userlist";
        }
        return "user/usermodify";
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam("userId") String userId) {
//        System.out.println(userId);
        if (userId == null || userId.equals("")) {
            logger.debug("不是合法的查询的id=============》");
            return "redirect:/user/userlist";
        }
        if (userService.delete(Integer.valueOf(userId))) {
            logger.debug("删除用户信息成功=================》");
        }
        return "redirect:/user/userlist";
    }
    /*@RequestMapping("/view/{userId}")
    public String view(@PathVariable String userId,Model model){
        if(userId == null || userId.equals("")){
            logger.debug("不是合法的查询的id=============》");
            return "redirect:/user/userlist";
        }
        model.addAttribute("user",userService.findById(Integer.valueOf(userId)));
        return "user/userview";
    }*/
    
    //单文件上传
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(User user, HttpServletRequest request,
                      @RequestParam(value = "userTx", required = false) MultipartFile upload,
                      HttpSession session) {
        
        String fileName = "";//上传文件名，
        //文件的上传路径
//        String path = session.getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
        
        //判断文件大小
        if (upload.getSize() > Constrant.UPLOAD_SIZE) {
            request.setAttribute("errMsg", "文件过大，请重新上传！");
            return "user/useradd";
        }
        //校验文件后缀名:jpg,png
        String originalFileName = upload.getOriginalFilename();//文件名
        String surfix = FilenameUtils.getExtension(originalFileName);//后缀名
        if (surfix.equals("jpg")) {
            fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Person.jpg";
            File file = new File(Constrant.UPLOAD_ORIGIN, fileName);
            if (!file.exists()) {//文件不存在
                file.mkdirs();
            }
            try {
                upload.transferTo(file);
            } catch (IOException e) {
//                e.printStackTrace();
                request.setAttribute("errMsg", "上传失败，请重新上传！");
                return "user/useradd";
            }
        } else {
            request.setAttribute("errMsg", "不支持的文件格式，请重新上传！");
            return "user/useradd";
        }
        
        User currentUser = (User) session.getAttribute(Constrant.USER_SESSION);
        user.setCreatedBy(currentUser.getId());
        //add upload FileName
        user.setIdPicPath(Constrant.UPLOAD_ORIGIN_PREFIX + fileName);
        //调用保存方法
        if (userService.addNewUser(user)) {
            //重定向到用户查询列表
            return "redirect:/user/userlist";
        }
        return "user/useradd";//失败
    }
    
    @RequestMapping("/userCodeExists")
    @ResponseBody
    public Object userCodeExists(@RequestParam String userCode) {
        
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("userCode", "T");
        
        if (userService.userCodeExists(userCode)) {
            resultMap.put("userCode", "T");
        } else {
            resultMap.put("userCode", "F");
        }
        
        return JSON.toJSONString(resultMap);
    }
    
    //    json返回对象，查看用户信息
    @RequestMapping("/view/{userId}")
    @ResponseBody
    public Object view(@PathVariable String userId, Model model) {
        if (userId == null || userId.equals("")) {
            logger.debug("不是合法的查询的id=============》");
            return "redirect:/user/userlist";
        }
        User user = userService.findById(Integer.valueOf(userId));
        return JSON.toJSONString(user);
    }
    
}
